
#import "DelugeWebRequest.h"

@implementation DelugeWebRequest

//
// session id
//
@synthesize sessionId														= _sessionId;

//
// init with method
//
- (id)initWithMethod:(NSString*)methodName
{
	//
	// call super
	//
	self																	= [super initWithMethod:methodName];
	return self;
}

//
// dealloc
//
- (void)dealloc
{
	self.sessionId															= nil;
	
	[super dealloc];
}

//
// setup request
//
- (void)setupRequest
{
	//
	// call super
	//
	[super setupRequest];
	
	//
	// setup cookie
	//
	if(self.sessionId.length)
	{
		NSDate* expires														= [NSDate dateWithTimeIntervalSinceNow:0x7fffffff];
		NSHTTPCookie* sessionIdCookie										= [self cookieWithName:@"_session_id" value:self.sessionId expires:expires];
		NSMutableArray* cookies												= [NSMutableArray arrayWithObject:sessionIdCookie];
		[self.request setAllHTTPHeaderFields:[NSHTTPCookie requestHeaderFieldsWithCookies:cookies]];
	}
}

//
// finished
//
- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
	NSArray* cookies														= [NSHTTPCookie cookiesWithResponseHeaderFields:[self.response allHeaderFields] forURL:[self.request URL]];
	for(NSHTTPCookie* cookie in cookies)
	{
		if([cookie.name isEqualToString:@"_session_id"])
			self.sessionId													= cookie.value;
	}
	
	[super connectionDidFinishLoading:connection];
}

@end
